<?php
namespace Admin\Model;
use Think\Model;
/**
 * 发票信息管理模型
 * 
 */

class InvoiceModel extends Model{

	protected $m_status = array('10'=>'待邮寄','20' =>'确认邮寄','30' => '邮寄中','40'=>'邮寄完成','50'=>'自取');

    //获取邮寄状态名称
	public function getStatus(){
		$status = array();
		foreach( $this->m_status as $kv=>$vt ){
			$item = array('k'=>$kv,'v'=>$vt);
			$status[] = $item;
		}
		return $status;
	}
    //根据流水账号pay_id和付款金额pay_mount保存先关数据到流水表
    public function setInvoiceMount($money,$pay_id,$invoice_id,$edit){
        $r = array('d'=>NULL,'i'=>'','r'=>1);
        if($edit&&$invoice_id){
            //编辑付款金额
            $wheres1 = array();
            $wheres1['invoice_id'] = array('eq',$invoice_id);
            $PayIdArr = M('invoice_pays')->field('pay_id')->where($wheres1)->select();
            for ($m=0; $m < count($PayIdArr); $m++) {
                $wheres2[$m] = array();
                $clearData[$m] = array();
                $wheres2[$m]['pay_id'] = array('eq',$PayIdArr[$m]['pay_id']);
                $clearData[$m]['invoice_mount'] = NULL;
                $clearPayMount = M('pay_record')->where($wheres2[$m])->save($clearData[$m]);
            }
        }
        $Totalmount = $money;
        $maps1 = array();
        $maps1['pay_id'] = array('in',$pay_id);
        $maps1['record_status'] = array('eq',1);//有效付款
        $payMount = M('pay_record')->field('payrecord_id,pay_id,pay_mount,record_status')->where($maps1)->order("pay_mount")->select();
        for ($j=0; $j < count($payMount); $j++) {
            $maps2[$j] = array();
            $addArr[$j] = array();
            $maps2[$j]['pay_id'] = $payMount[$j]['pay_id'];
            $maps2[$j]['payrecord_id'] = $payMount[$j]['payrecord_id'];
            if($Totalmount>=$payMount[$j]['pay_mount']){
                $addArr[$j]['invoice_mount'] = $payMount[$j]['pay_mount'];
            }else{
                $addArr[$j]['invoice_mount'] = $Totalmount;
            }
            $addInvoiceMount[$j] = M('pay_record')->where( $maps2[$j] )->save( $addArr[$j] );
            $Totalmount -= $payMount[$j]['pay_mount'];
            if(!$addInvoiceMount[$j]){
                $r['i'] = 0;
                $r['i'] = '发票添加失败，请重新添加！';
                return $r;
            }
        }
        return $r;
    }
    //页面添加发票
    public function add_invoice($add_data,$delivetype,$add_delivery){
        $uinfo = UserModel::loadFromSession();
        $r = array('d'=>NULL,'i'=>'','r'=>0,'invoice_id' => 0,'pic_alt'=>'');
        
        $wheres = array();
        $wheres['customer_id'] = array('eq',$add_data['customer_id']);
        $MPayrecord = M('pay_record');
        //获取业务员信息
        $userInf = $MPayrecord
                ->field("sales_manager,sales_person,sales_sector,sales_sub_company")
                ->where( $wheres )
                ->find();
        if( !$uinfo )
            $r['i'] = '加载用户信息失败';
        else{
            $d = array();
            $da = array();
            $d['title'] = $add_data['title'];
            $d['money'] = $add_data['money'];
            $d['tax'] = $add_data['tax'];

            if($add_data['payee']) $d['payee'] = $add_data['payee'];
            else $d['payee'] = NULL;
            if($add_data['remark']) $d['remark'] = $add_data['remark'];
            else $d['remark'] = "";

            $d['type'] = $add_data['type'];
            $d['creator'] = $uinfo['user_id'];
            $d['creator_role'] = $uinfo['role_id'];
            $d['creator_sector'] = $uinfo['sector_id'];
            $d['customer_id'] = $add_data['customer_id'];
            $d['status'] = $add_data['status'];
            $d['sales_id'] = $userInf['sales_person'];
            $d['sales_sector'] = $userInf['sales_sector'];
            $d['sales_subcompany'] = $userInf['sales_sub_company'];
            $d['sales_manager'] = $userInf['sales_manager'];
            $d['create_time'] = date('Y-m-d H:i:s');
            $d['update_time'] = date('Y-m-d H:i:s');
            $addID = $this->add( $d );
            if( $addID ){
                //关联发票对应流水存入数据库
                $r['r'] = $addID;
                $da['pay_id'] = explode(',',$add_data['pay_id']);
                for ($i=0; $i < count($da['pay_id']); $i++) {
                    $das[$i]['pay_id'] = $da['pay_id'][$i];
                    $das[$i]['invoice_id'] = $addID;
                    $das[$i]['remark'] = $add_data['remark'];
                    $addInvoicePays[$i] = M('invoice_pays')->add($das[$i]);
                    if(!$addInvoicePays[$i]){
                        $r['i'] = '发票添加失败，请重新添加！';
                        return $r;
                    }
                }
                if($delivetype == 1){   //发票邮寄
                    //关联邮寄信息存入数据库
                    $Delivery = D("delivery");
                    $add_deliv = array();
                    $add_deliv['recipients'] = $add_delivery['recipients'];
                    $add_deliv['address'] = $add_delivery['address'];
                    $add_deliv['phone'] = $add_delivery['phone'];
                    $add_deliv['send_time'] = $add_delivery['send_time'];
                    $add_deliv['remark'] = $add_delivery['remark'];
                    $add_deliv['sales_id'] = $userInf['sales_person'];
                    $add_deliv['sales_manager'] = $userInf['sales_manager'];
                    $add_deliv['sales_subcompany'] = $userInf['sales_sub_company'];
                    $add_deliv['customer_id'] = $add_data['customer_id'];
                    $add_deliv['sales_sector'] = $userInf['sales_sector'];
                    $add_deliv['invoice_id'] = $addID;
                    $addDeliveryId = D("delivery")->deliveryAdd($add_deliv);
                    if(!$addDeliveryId['rcode']){
                        $r['i'] = '发票添加失败，请重新添加！';
                        return $r;
                    }else{
                        //发票数据绑定邮寄数据
                        $mapp = array();
                        $add_bind = array();
                        $mapp['invoice_id'] = array('eq',$addID);
                        $add_bind['delivery_id'] = $addDeliveryId['delivery_id'];
                        $bindStatus = $this->where( $mapp )->save( $add_bind );
                        if(!$bindStatus){
                            $r['i'] = '发票添加失败，请重新添加！';
                            return $r;
                        }
                    }
                }
                //关联流水表中发票金额：若多条流水合并开发票，则优先全开小金额
                $this->setInvoiceMount($add_data['money'],$add_data['pay_id'],'','');
                $r['i'] = 'OK';
                $r['d'] = $this->where( 'invoice_id='.$addID )->find();
            }else{
                $r['i'] = '发票添加失败，请重新添加！';
            }
        }
        $r['invoice_id'] = $addID;
        return $r;
    }

    //编辑发票
    public function update_invoice($edit_data,$delivery_id,$edit_delivery){
        $r = array('d'=>NULL,'i'=>'','r'=>0);
        if( $edit_data['invoice_id']) {
            $wheres = array();
            $wheres['invoice_id'] = array('eq', $edit_data['invoice_id'] );
            $wheres['is_delete'] = array('neq', 1);
            $editInvoice = $this->where( $wheres )->find();
            if( $editInvoice ){
                $d = array();
                $d['update_time'] = date('Y-m-d H:i:s');
                $d['title'] = $edit_data['title'];
                $d['money'] = $edit_data['money'];
                $d['tax'] = $edit_data['tax'];
                if($edit_data['type'] == 2){
                    $d['payee'] = NULL;
                }else{
                    $d['payee'] = $edit_data['payee'];
                }
                $d['remark'] = $edit_data['remark'];
                $editID = $this->where( $wheres )->save( $d );
                if( $editID ){
                    if($delivery_id){
                        //编辑邮寄信息
                        $edit_delive = array();
                        $edit_delive['delivery_id'] = $edit_delivery['delivery_id'];
                        $edit_delive['recipients'] = $edit_delivery['recipients'];
                        $edit_delive['address'] = $edit_delivery['address'];
                        $edit_delive['phone'] = $edit_delivery['phone'];
                        $edit_delive['send_time'] = $edit_delivery['send_time'];
                        $edit_delive['remark'] = $edit_delivery['remark'];
                        $editDeliveId = D("delivery")->deliveryEeditor($edit_delive);
                        if(!$editDeliveId['rcode']){
                            $r['i'] = '发票更新失败，请重新编辑！';
                            return $r;
                        }
                    }
                    //关联流水表中发票金额：若多条流水合并开发票，则优先全开小金额
                    $this->setInvoiceMount($edit_data['money'],$edit_data['pay_id'],$edit_data['invoice_id'],1);
                    $maps1 = array();
                    $maps1['invoice_id'] = array('eq', $edit_data['invoice_id']);
                    //删除原数据，重新绑定对应流水到数据库
                    $delPaysId = M('invoice_pays')->where($maps1)->delete();
                    $da = array();
                    $da['pay_id'] = explode(',',$edit_data['pay_id']);
                    for ($i=0; $i < count($da['pay_id']); $i++){
                        $maps2[$i]['pay_id'] = $da['pay_id'][$i];
                        $maps2[$i]['invoice_id'] = $edit_data['invoice_id'];
                        $maps2[$i]['remark'] = $edit_data['remark'];
                        $addInvoicePays[$i] = M('invoice_pays')->add($maps2[$i]);
                        if(!$addInvoicePays[$i]){
                            $r['i'] = '发票更新失败，请重新编辑！';
                            return $r;
                        }
                    }
                    $r['r'] = 1;
                    $r['d'] = $this->where( $wheres )->find();
                    $r['i'] = 'OK';
                } else{
                    $r['i'] = '发票更新失败！';
                }
            } else
                $r['i'] = '抱歉，数据不存在！';
        } else{
            $r['i'] = '参数错误！';
        }
        return $r;
    }

    //修改图片说明信息
    public function changePicAlt($invoice_id,$pic_alt){
        $r = array('d'=>NULL,'i'=>'OK','r'=>0);
        $wheres = array();
        $wheres['invoice_id'] = array('eq',$invoice_id);
        $find = M('invoice_pic')->where($wheres)->find();
        if($find){
            $d = array();
            $d['pic_alt'] = $pic_alt;
            $changs = M('invoice_pic')->where($wheres)->save($d);
            if($changs || $changs == 0){
                $r['r'] = 1;
                $r['i'] = '专票信息更改完成';
                $r['d'] = M('invoice_pic')->where( $wheres )->find();
            }else{
                $r['i'] = '专票信息更改失败';
            }
        }else{
            $r['i'] = '获取发票信息失败！';
        }
        return $r;
    }

    //添加图片信息
    public function addInvoicePic($dataImg){
        $r = array('d'=>NULL,'i'=>'','r'=>0);
        if($dataImg){
            $d = array();
            $d['invoice_id'] = $dataImg['invoice_id'] ? $dataImg['invoice_id'] : '';
            $d['pic_order'] = $dataImg['pic_order'] ? $dataImg['pic_order'] : '';
            $d['pic_path'] = $dataImg['pic_path'] ? $dataImg['pic_path'] : '';
            $d['pic_alt'] = $dataImg['pic_alt'] ? $dataImg['pic_alt'] : '';
            $picAdd = M('invoice_pic')->add($d);
            if( $picAdd ){
                $r['r'] = 1;
                $r['i'] = 'OK';
                $r['d'] = $picAdd;
            }else{
                $r['i'] = '图片信息添加失败，请重新添加！';
            }
        }else{
            $r['i'] = '获取图片信息失败！';
        }
        return $r;
    }
    
    //截取字符串
    public function cutStr($begin,$end,$str){
        $str1 = explode($begin,$str);
        $str2 = explode($end,$str1[1]);
        $vals = $str2[0];
        return $vals;
    }

}
?>